class CancelToken {
    // 是否已经 被标记为 cancel了
    hasCanceledFlag: boolean;
    // 取消原因
    reason?: string;
    promise: Promise<CancelToken>;
    constructor(executor: (fn: (msg?: string) => void) => void) {
        this.hasCanceledFlag = false;
        let resolvePromise: ((cancel: CancelToken) => void) | undefined = undefined;
        this.promise = new Promise((resolve) => {
            resolvePromise = resolve;
        });
        let token = this;

        executor(function cancel(msg: string = "手动取消") {
            if (token.hasCanceledFlag) {
                // 已经处理过了
                return;
            }
            token.hasCanceledFlag = true;
            token.reason = msg;
            resolvePromise && resolvePromise(token);
        });
    }

    static source() {
        let cancelFn: (msg?: string) => void;
        let token = new CancelToken(function (c) {
            // 保存一下
            cancelFn = c;
        });

        return {
            token,
            // @ts-ignore
            cancel: cancelFn,
        };
    }
}

export default CancelToken;
